package com.laobiao.file_netty_lib.util;

import java.io.File;
import java.io.FileInputStream;
import java.nio.file.NoSuchFileException;
import java.util.Arrays;

import com.laobiao.file_netty_lib.exception.FileBaseException;


public class CheckCodeUtil{
    /**
     * 默认校验码，空文件使用
     */
//    private static byte[] checkCode={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    /**
     * 生成文件校验码
     * 
     * @param f 文件
     * @return
     * @throws NoSuchFileException
     */
    public static byte[] getCheckCode(File f)  {
        if(f==null){
            throw new FileBaseException("文件不能为空！"+f.getName(), FileBaseException.ERR_PARAM_NULL);
        }
        if(f.isDirectory()){
            throw new FileBaseException("不支持目录生成校验码！"+f.getAbsolutePath(), FileBaseException.ERR_PARAM_WRONG);
        }
        FileInputStream fin=null;
        try {
            fin=new FileInputStream(f);
            if(f.length()==0){
                return new byte[20];
            }
            if(f.length()<20){
//                code=new byte[(int)f.length()];
//                fin.read(code);
//                return code;
            	 return new byte[20];
            }else{
                byte[] b1=new byte[10];
                byte[] b2=new byte[10];
                //读前十个字节
                fin.read(b1);
                //读后十个字节
                fin.skip(f.length()-20);
                fin.read(b2);
                return ByteUtil.mergByte(b1, b2);
            }
        } catch (Exception e) {
            //TODO: handle exception
            throw new FileBaseException("生成校验码失败！"+f.getAbsolutePath(),e, FileBaseException.ERR_PARAM_WRONG);
        }finally{
            try {
                fin.close();
            } catch (Exception e) {
                //TODO: handle exception
            }
        }
    }
    
    /**
     * 生成数据校验码
     * @param data
     * @return
     */
    public static byte[] getCheckCode(byte[] data)  {
    	 if(data==null ) {
    		 throw new FileBaseException("生成校验码失败,数据不能为空！", FileBaseException.ERR_PARAM_NULL);
    	 }
    	 if(data.length==0){
             return new byte[20];
         }
         if(data.length<20){
         	 return new byte[20];
         }else{
             byte[] b1=Arrays.copyOfRange(data, 0, 10);
             byte[] b2=Arrays.copyOfRange(data, data.length-10, data.length);
             return ByteUtil.mergByte(b1, b2);
         }
    }
    

}